<script setup>
import {
  getBizEquInfo,
  addBizEquInfo,
  updateBizEquInfo,
  findMaxSort,
  getlocationBylatlng
} from "@/api/biz/bizEquInfo";
import { listBizHousingInfo } from "@/api/biz/bizHousingInfo";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { listBizCompany } from "@/api/biz/bizCompany";

const props = defineProps({
  id: {
    type: [Number, String],
    default: ""
  }
});

const formRef = ref();

const data = ref({
  loading: false,
  form: {
    id: props.id,
    equLng: 111.361,
    equLat: 30.64441,
    equAddress: ""
  },
  rules: {
    name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    userName: [
      { required: true, message: "请输入登陆账号", trigger: "blur" },
      { validator: getcheckUserNameUnique }
    ]
  },
  housingList: [],
  loading: false,
  dialogVisible: false,
  sreachAreaList: [],
  listCompany: []
});

onMounted(() => {
  if (data.value.form.id != "") {
    getInfo();
  } else {
    findMaxSort().then((res) => {
      data.value.form.sort = res.data;
    });
  }
  getListHousing();
  getPosition();
  getListCompany();
});

function getInfo() {
  data.value.loading = true;
  getBizEquInfo(props.id).then((res) => {
    data.value.loading = false;
    data.value.form = res.data;
  });
}

// 获取公司
function getListCompany() {
  listBizCompany({ pageSize: 50 }).then((res) => {
    data.value.listCompany = res.data.list;
  });
}

function getListHousing(value) {
  data.value.loading = true;
  setTimeout(() => {
    data.value.loading = false;
    listBizHousingInfo({
      pageSize: 20,
      pageNum: 1,
      housingName: value
    }).then((res) => {
      data.value.housingList = res.data.list;
    });
  }, 10);
}

function getcheckUserNameUnique(rule, value, callback) {
  if (data.value.form.id !== "" || data.value.form.id !== undefined) {
    callback();
  }
  const msg = "登陆账号已存在";
  if (value === "") {
    callback();
  } else {
    const checkData = {
      userName: value
    };
    checkUserNameUnique(checkData).then((response) => {
      if (response.data.code === "1") {
        callback();
      } else {
        callback(msg);
      }
    });
  }
}
defineExpose({
  submit(callback) {
    if (data.value.form.id == "") {
      formRef.value.validate((valid) => {
        if (valid) {
          addBizEquInfo(data.value.form).then(() => {
            ElMessage.success({
              message: "保存成功",
              center: true
            });
            callback && callback();
          });
        }
      });
    } else {
      formRef.value.validate((valid) => {
        if (valid) {
          updateBizEquInfo(data.value.form).then(() => {
            ElMessage.success({
              message: "修改成功",
              center: true
            });
            callback && callback();
          });
        }
      });
    }
  }
});
var map;
var searchService;
var latlngBounds;

function initMap() {
  var center = new qq.maps.LatLng(
    data.value.form.equLat,
    data.value.form.equLng
  );

  //初始化地图
  map = new qq.maps.Map(document.getElementById("container"), {
    rotation: 0, //设置地图旋转角度
    pitch: 0, //设置俯仰角度（0~45）
    zoom: 12, //设置地图缩放级别
    center: center //设置地图中心点坐标
  });
  var ap = new qq.maps.place.Autocomplete(document.getElementById("place"));
  var keyword = "";
  new qq.maps.Circle({
    center: new qq.maps.LatLng(center),
    radius: 5000,
    map: map
  });
  if (data.value.form.id != "") {
    var item = {
      address: data.value.form.equAddress,
      latLng: {
        lat: data.value.form.equLat,
        lng: data.value.form.equLng
      }
    };
    searchMarker(item);
  }
  //调用Poi检索类。用于进行本地检索、周边检索等服务。
  searchService = new qq.maps.SearchService({
    complete: function (results) {
      if (results.type === "CITY_LIST") {
        searchService.setLocation(results.detail.cities[0].cityName);
        searchService.search(keyword);
        return;
      }
      data.value.sreachAreaList = [];
      var pois = results.detail.pois;
      latlngBounds = new qq.maps.LatLngBounds();
      for (var i = 0, l = pois.length; i < l; i++) {
        var poi = pois[i];
        latlngBounds.extend(poi.latLng);
        // var marker = new qq.maps.Marker({
        //     map:map,
        //     position: poi.latLng
        // });

        // marker.setTitle(poi.name);
        data.value.sreachAreaList.push(poi);
        console.log(JSON.stringify(poi));
      }
      map.fitBounds(latlngBounds);
    }
  });
  //添加监听事件
  qq.maps.event.addListener(ap, "confirm", function (res) {
    keyword = res.value;
    var center = new qq.maps.LatLng(
      data.value.form.equLat,
      data.value.form.equLng
    );
    searchService.searchNearBy(keyword, center, 5000);
  });
}
function inputSearch() {
  var center = new qq.maps.LatLng(
    data.value.form.equLat,
    data.value.form.equLng
  );
  searchService.searchNearBy(data.value.form.sreachCode, center, 5000);
}
function searchByKeyword() {}
function openMap() {
  data.value.dialogVisible = true;

  setTimeout(() => {
    initMap();
  }, 100);
}
function getPosition() {
  var geolocation = new qq.maps.Geolocation(
    "7NRBZ-6VI3O-CXBW5-S7KC2-DB4LF-Y4FFS",
    "referer=mt"
  );
  geolocation.getLocation(showPosition, errorPosition);
}
function showPosition(position) {
  console.log("定位信息", position);
  if (data.value.form.id != "") {
  } else {
    data.value.form.equLat = position.lat;
    data.value.form.equLng = position.lng;
  }
}
function errorPosition() {
  console.log("定位失败");
  //继续定位
  // this.getPosition();
}
function searchMarker(item) {
  console.log(item);
  var center = new qq.maps.LatLng(item.latLng.lat, item.latLng.lng);
  data.value.form.equAddress = item.address;
  data.value.form.address = item.address;
  data.value.form.equLat = item.latLng.lat;
  data.value.form.equLng = item.latLng.lng;
  map = new qq.maps.Map(document.getElementById("container"), {
    rotation: 0, //设置地图旋转角度
    pitch: 0, //设置俯仰角度（0~45）
    zoom: 16, //设置地图缩放级别
    center: center, //设置地图中心点坐标
    offset: { x: 4000, y: 0 }
  });
  var marker = new qq.maps.Marker({
    position: map.getCenter(),
    draggable: true,
    map: map
  });
  qq.maps.event.addListener(marker, "dragend", function (e) {
    // 监听标记拖动
    var latLng = marker.getPosition();
    map.setCenter(latLng);
    let lats = latLng.lat.toFixed(6);
    let lng = latLng.lng.toFixed(6);
    var key = "7NRBZ-6VI3O-CXBW5-S7KC2-DB4LF-Y4FFS";
    // 换地址
    getlocationBylatlng({ lat: lats, lng: lng, key: key }).then((res) => {
      data.value.form.equAddress = res.data.result.address;
      data.value.form.address = res.data.result.address;
      data.value.form.equLat = lats;
      data.value.form.equLng = lng;
    });
  });
}
</script>

<template>
  <div v-loading="data.loading">
    <el-form
      ref="formRef"
      :model="data.form"
      :rules="data.rules"
      label-width="120px"
      label-suffix=" "
      label-position="top"
      style="padding: 0 20px"
    >
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="所属公司" prop="companyId">
            <el-select v-model="data.form.companyId" style="width: 100%">
              <el-option
                :value="item.id"
                :label="item.companyName"
                v-for="(item, index) in data.listCompany"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择小区" prop="housingName">
            <el-select
              v-model="data.form.housingId"
              clearable
              placeholder="小区信息"
              style="width: 100%"
              filterable
              remote
              :remote-method="getListHousing"
              :loading="loading"
              reserve-keyword
              remote-show-suffix
              :suffix-transition="false"
            >
              <el-option
                v-for="item in data.housingList"
                :key="item.id"
                :label="item.housingName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="驿站名称" prop="equXinghao">
            <el-input placeholder="驿站名称" v-model="data.form.equXinghao" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="驿站编号" prop="equNo">
            <el-input placeholder="驿站编号" v-model="data.form.equNo" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="地址信息" prop="equAddress">
            <el-input placeholder="地址信息" v-model="data.form.equAddress">
              <template #append
                ><el-button type="primary" size="small" text @click="openMap">
                  <el-icon>
                    <svg-icon name="ep:circle-plus" />
                  </el-icon>
                  选择地址</el-button
                ></template
              >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="data.form.sort" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="data.form.status"
              active-text="否"
              inactive-text="是"
              active-value="1"
              inactive-value="0"
              inline-prompt
              style="
                --el-switch-off-color: #409eff;
                --el-switch-on-color: #ff4949;
              "
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="data.form.remark" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      v-model="data.dialogVisible"
      title="请选择驿站定位"
      width="80vw"
      top="5vh"
      :modal-append-to-boay="false"
      style="height: 60vh"
      v-if="data.dialogVisible"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="小区搜索" prop="sreachCode">
                <el-input
                  v-model="data.form.sreachCode"
                  id="place"
                  placeholder="请输入需要搜索的关键字"
                >
                  <template #append
                    ><el-button
                      type="primary"
                      size="small"
                      text
                      @click="inputSearch"
                    >
                      <el-icon>
                        <svg-icon name="ep:search" />
                      </el-icon>
                      搜索</el-button
                    ></template
                  >
                </el-input>
              </el-form-item>
            </el-col>
            <div class="addListBox">
              <el-col :span="24" v-for="(item, index) in data.sreachAreaList">
                <div class="additem" @click="searchMarker(item)">
                  <div class="name">{{ item.name }}</div>
                  <div class="addinfo">{{ item.address }}</div>
                </div>
              </el-col>
            </div>
          </el-row>
        </el-col>
        <el-col :span="18">
          <el-row :gutter="30">
            <el-col :span="24">
              <div class="container_map">
                <div
                  id="container"
                  v-if="data.dialogVisible"
                  style="width: 100vw; height: 60vh"
                ></div>
              </div>
            </el-col>
            <el-col :span="24" style="margin-top: 20px">
              <el-form-item label="地址信息：" prop="sreachCode">
                <el-input v-model="data.form.address" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="data.dialogVisible = false"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.container_map {
  overflow: hidden;
}
.addListBox {
  height: 60vh;
  overflow-y: auto;
}
.additem {
  padding: 10px;
  border-bottom: 1px dotted #eee;
  cursor: pointer;
}
.additem:hover {
  background: rgb(174 174 233 / 10%);
}
.additem .name {
  font-size: 16px;
  color: #222;
}
.additem .addinfo {
  color: #666;
  font-size: 14px;
}
</style>
